package com.longrise.android.byjk.plugins.aboutme.personalInfo;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.longrise.android.byjk.R;
import com.longrise.android.byjk.plugins.main.MainActivity;
import com.longrise.common.base.BaseActivity;
import com.longrise.android.byjk.model.UserInfor;
import com.longrise.android.byjk.plugins.login.LoginActivity;
import com.longrise.android.byjk.plugins.vip.VipDescriptionActivity;
import com.longrise.android.byjk.widget.view.InputBoxView;

/**
 * Created by godliness on 2017/3/23.
 * 开通快捷登录
 */
public class OpenLoginActivity extends BaseActivity implements View.OnClickListener, PersonalInfoContract.OpenLoginView, TextWatcher {

    private static final String TAG = "OpenLoginActivity";

    private final String SAVEINSTANCE_IS_INTEGRAL = "SAVEINSTANCE_IS_INTEGRAL";
    private final String SAVEINSTANCE_RUN_LOGIN = "SAVEINSTANCE_RUN_LOGIN";

    public static final String EXTRA_PARAMS = "EXTRA_PARAMS";
    public static final String LOGIN_PAGE_FROM = "login_page_from";  //是否来自自动登录页面
    public static final int NON_AUTO_LOGIN = 1;  //登录界面过来
    public static final int AUTO_LOIN = 2;  //自动登录过来

    private static int mFromPage = AUTO_LOIN;

    private Toolbar mTitle;
    private RelativeLayout mRight;

    /**
     * 已开通快捷登录时layout
     */
    private TextView mOpenLogin;
    /**
     * 未开通快捷登录时layout
     */
    private LinearLayout mNoneLogin;

    private EditText mPhone;
    private TextView mGetCode;
    private InputBoxView mCode;
    private View mLoading;

    private Button mConfirm;

    private PersonalInfoContract.OpenPresenters mPersenter;

    private boolean mRunLogin;  //是否已经开通
    private boolean mIntegralFrom; //是否是积分任务进入

    /**
     * 是否跳过
     */
    private boolean mJump;
    private TextView mTvTips;

    private ImageView mForgetPwd;

    @Override
    public int getContentViewId(@Nullable Bundle savedInstanceState) {
        if (savedInstanceState != null) {
            mJump = savedInstanceState.getBoolean(EXTRA_PARAMS);
            mIntegralFrom = savedInstanceState.getBoolean(SAVEINSTANCE_IS_INTEGRAL);
            mRunLogin = savedInstanceState.getBoolean(SAVEINSTANCE_RUN_LOGIN);
        }
        return R.layout.activity_openlogin;
    }

    public void initPresenter() {
        mPersenter = new OpenLoginPresenter(this, this);
        mPersenter.init();

        if (mRunLogin) {
            mPersenter.loginPhone();
        }
    }

    @Override
    public void initView() {
        initTitle();
        initLoginLayout();
        initTips();
        onEvent();

        getExtraData();
        initPresenter();
    }

    private void initLoginLayout() {
        //是否已经开通快捷登录  login == "1"为已开通
        String login = UserInfor.getInstance().getIsopenmobilelogin();
        mRunLogin = login != null && login.equals("1") ? true : false;
        //已开通快捷登录layout
        mOpenLogin = (TextView) findViewById(R.id.tv_isopenlogin);
        mOpenLogin.setVisibility(mRunLogin ? View.VISIBLE : View.GONE);

        //未开通快捷登录layout
        mNoneLogin = (LinearLayout) findViewById(R.id.linear_noneopenlogin);
        mNoneLogin.setVisibility(mRunLogin ? View.GONE : View.VISIBLE);

        mPhone = (EditText) findViewById(R.id.forgetpasword_text);
        mGetCode = (TextView) findViewById(R.id.forgetpasword_pic2);
        mCode = (InputBoxView) findViewById(R.id.iv_cp_confrimcode);
        mConfirm = (Button) findViewById(R.id.btn_cp_confrim);
        mCode.setRightClickMode(InputBoxView.USERIF);
        mConfirm.setEnabled(false);
        mTvTips = (TextView) findViewById(R.id.tv_cp_phone);

        mLoading = findViewById(R.id.rela_load_xqpc);
        mLoading.setVisibility(View.GONE);

        mForgetPwd = (ImageView)findViewById(R.id.forgetpasword_pic1);
        mPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String phone = mPhone.getText().toString().trim();
                if(TextUtils.isEmpty(phone)||"".equals(phone)){
                    mForgetPwd.setSelected(false);
                }else{
                    mForgetPwd.setSelected(true);
                }

            }
        });

    }

    private void initTitle() {
        mTitle = (Toolbar) findViewById(R.id.byjk_toolbar);
        mTitle.setTitle("");
        setSupportActionBar(mTitle);

        mRight = (RelativeLayout) mTitle.findViewById(R.id.bb_toolbar_right_rl_tv);
        mRight.setOnClickListener(this);

    }

    //xkj 20170420
    private void initTips() {
        String tips = "";
        String usersfzh = UserInfor.getInstance().getUsersfzh();
        String userName = UserInfor.getInstance().getUserName();
        if (TextUtils.isEmpty(usersfzh)) {//身份证号码为空
            tips = userName;
        } else {
            tips = usersfzh;
        }
        mTvTips.setText(tips);
    }

    /**
     * 是否显示跳过按钮
     * 传递EXTRA_PARAMS参数true
     */
    private void getExtraData() {
        Intent extraIntent = getIntent();
        if (extraIntent != null && extraIntent.hasExtra(EXTRA_PARAMS)) {
            mJump = extraIntent.getBooleanExtra(EXTRA_PARAMS, false);
        }
        mRight.setVisibility(mJump ? View.VISIBLE : View.GONE);
        mFromPage = extraIntent.getIntExtra(LOGIN_PAGE_FROM, 0);
        //积分任务进入
//        if (extraIntent != null && extraIntent.hasExtra(BBWebHelper.FROM_PAGE)) {
//            String value = extraIntent.getStringExtra(BBWebHelper.FROM_PAGE);
//            if (value != null && value.equals(BBWebHelper.PAGE_NAME)) {
//                mIntegralFrom = true;
//            } else {
//                mIntegralFrom = false;
//            }
//        }
    }

    private void onEvent() {
        if (mGetCode != null) {
            mGetCode.setOnClickListener(this);
        }
        if (mConfirm != null) {
            mConfirm.setOnClickListener(this);
        }
        if (mTitle != null) {
            mTitle.setNavigationOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    close(mRunLogin);
                }
            });
        }

        mPhone.addTextChangedListener(this);
        mCode.getEditText().addTextChangedListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.forgetpasword_pic2:
                mPersenter.toGetCode(mPhone.getText().toString().trim());
                break;

            case R.id.btn_cp_confrim:
                mPersenter.confirm(mPhone.getText().toString().trim(), mCode.getText().toString().trim());
                break;

            case R.id.bb_toolbar_right_rl_tv:
                toSkip();
                break;
        }
    }

    private CountDownTimer mTimer = new CountDownTimer(60000, 1000) {

        @Override
        public void onTick(long millisUntilFinished) {
            mGetCode.setText("重新获取(" + millisUntilFinished / 1000 + "s)");
        }

        @Override
        public void onFinish() {
            resetVftoNorm();
        }
    };

    /**
     * 恢复获取验证码按钮状态
     */
    private void resetVftoNorm() {
        codeBtnStatus(true, getString(R.string.getmoblieconfrimcode), "#FF9900");
    }

    /**
     * 设置验证码按钮状态
     */
    private void codeBtnStatus(boolean isClickable, String text, String textColor) {
        mGetCode.setClickable(isClickable);
        mGetCode.setText(text);
        mGetCode.setTextColor(Color.parseColor(textColor));
    }

    /**
     * 设置确认按钮状态
     */
    private void setBtnStatus(boolean isClick) {
        mConfirm.setClickable(isClick);
    }

    @Override
    public void setPhoneHint(String hint) {
        mPhone.setHint(hint);
    }

    @Override
    public void setCodeHint(String hint) {
        mCode.getEditText().setHint(hint);
    }

    @Override
    public void setTitle(String title) {
        mTitle.setTitle(title);
    }

    @Override
    public void setVftoNorm() {
        resetVftoNorm();
    }

    @Override
    public void setCodeBtnStatus(boolean isClickable, String text, String textColor) {
        codeBtnStatus(isClickable, text, textColor);
    }

    @Override
    public void setConfrimBtnState(boolean isClick) {
        setBtnStatus(isClick);
    }

    @Override
    public void close(boolean state) {
        if (state) {  //true开通成功
            if (mFromPage == AUTO_LOIN || mFromPage == NON_AUTO_LOGIN) {
                startActivity(MainActivity.class);
            } else {
                activityResult(state);
            }
        } else {
            if (mFromPage == AUTO_LOIN) {
                startActivity(LoginActivity.class);
            } else if (mFromPage == NON_AUTO_LOGIN) {
                finish();
            } else {
                activityResult(state);
            }
        }
    }

    private void activityResult(boolean state) {
        Intent resultIntent = new Intent();
        resultIntent.putExtra("key", state);
        setResult(100, resultIntent);
        finish();
    }

    /**
     * 跳过 xkj
     */
    private void toSkip() {
        if (UserInfor.getInstance().getViptype() == 1) { //vip没有升级的用户提示升级vip
            Bundle bundle = new Bundle();
            bundle.putInt(VipDescriptionActivity.MODE, VipDescriptionActivity.LOGIN);
            startActivity(VipDescriptionActivity.class, bundle);
        } else {
            startActivity(MainActivity.class);
        }
    }

    @Override
    public void setLoginPhone(CharSequence params) {
        mOpenLogin.setText(params);
    }

    @Override
    public void setRightText(String text) {
        TextView rightTV = (TextView) mTitle.findViewById(R.id.iv_toolbar_right_tv);
        rightTV.setText(text);
    }

    @Override
    public void isLoading(boolean isloading) {
        mLoading.setVisibility(isloading ? View.VISIBLE : View.GONE);
    }

    @Override
    public boolean getIsJump() {
        return mJump;
    }

    @Override
    public boolean getFrom() {
        return mIntegralFrom;
    }

    /**
     * 在没有积分情况时，开通快捷登录之后，OpenLoginActivity直接关闭，目前
     * 存在积分任务，不能直接关闭，故添加此方法修改页面状态
     */
    @Override
    public void updateContentState() {
        mRunLogin = true;
        mNoneLogin.setVisibility(View.GONE);
        mOpenLogin.setVisibility(View.VISIBLE);
        mPersenter.loginPhone();
    }

    @Override
    public CountDownTimer getTimer() {
        return mTimer;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            close(mRunLogin);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putBoolean(EXTRA_PARAMS, mJump);
        outState.putBoolean(SAVEINSTANCE_IS_INTEGRAL, mIntegralFrom);
        outState.putBoolean(SAVEINSTANCE_RUN_LOGIN, mRunLogin);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    //-------------输入框字符变化----------------
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        boolean b = checkText();
        if (b) {
            mConfirm.setEnabled(true);
        } else {
            mConfirm.setEnabled(false);
        }
    }
    //------------------------------------------

    /**
     * 检查是否全部填写
     *
     * @return 全部有填写 返回true
     */
    private boolean checkText() {
        //手机号
        String phoneNum = mPhone.getText().toString().trim();
        if (TextUtils.isEmpty(phoneNum)) {
            return false;
        }
        //短信验证码
        String mIbvVfcodeText = mCode.getText();
        if (TextUtils.isEmpty(mIbvVfcodeText)) {
            return false;
        }
        return true;
    }


}
